<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link type="text/css" href="/jQuery-Timepicker-Addon/1.6.3/css/jquery-ui-timepicker-addon.css" rel="stylesheet"/>
    <link rel="stylesheet" href="/select2/css/select2.css"/>
    <link rel="stylesheet" href="/jqGrid/css/ui.jqgrid.css"/>
    <!--<link rel="stylesheet" href="/jqGrid/css/ui.jqgrid-for-bootstrap4.css"/>-->
    <link rel="stylesheet" type="text/css" href="/themes/<%= theme %>/jquery-ui.min.css"/>

    <script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="/js/jquery-ui.js"></script>
    <script type="text/javascript" src="/jqGrid/js/grid.locale-cn.js"></script>
    <script type="text/javascript" src="/jqGrid/js/jquery.jqGrid.js"></script>
    <script type="text/javascript" src="/select2/js/pinyin.min.js"></script>
    <script type="text/javascript" src="/select2/js/select2.full.js"></script>
    <script type="text/javascript" src="/select2/js/zh-CN.js"></script>
    <script type="text/javascript" src="/jQuery-Timepicker-Addon/1.6.3/js/jquery-ui-timepicker-addon.js"></script>
    <script type="text/javascript" src="/jQuery-Timepicker-Addon/1.6.3/js/jquery-ui-timepicker-zh-CN.js"></script>
    <script type="text/javascript" src="/js/index.js"></script>
    <script type="text/javascript" src="/js/jsNodeId.js"></script>
    <script type="text/javascript" src="/js/jquery.print.js"></script>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            font-size: small;
        }

        html, body {
        / / overflow-x: hidden;
            -ms-overflow-style: scrollbar;
            height: 100%;
            box-sizing: border-box;
        }
        @media print {

        }

    </style>
</head>
<body class="ui-widget-content">
<div id="list_1" style="padding:5px;" class="print_table">
    <table id="list"></table>
    <div id="pager" class="no-print"></div>
</div>
<div id="list_2" style="padding:5px;box-sizing: content-box;">
    <table id="list1"></table>
    <div id="pager1"></div>
</div>
<div id="dialog-message" style="display: none;" title="信息提示">
    <p id="info"></p>
</div>
<script type="text/javascript">
	$("#dialog-message").dialog({
		autoOpen: false,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.3
		},
		buttons: {
			'关闭': function () {
				$(this).dialog("close");
			}
		}
	});
	$(window).resize(function () {
		$(window).unbind("onresize");
		$("#list").jqGrid('setGridWidth', $("#list_1").width());//.jqGrid('setGridHeight', winWh.WinH-86);
		$("#list1").jqGrid('setGridWidth', $("#list_2").width()); // $(window).width() - 8
		$(window).bind("onresize", this);
	});

	function getCustomersOptions() {
		let data = {};
		runAjax('get', '/sales/customers/lists', {}, function (err, result) {
			if (!err) {
				for (let i = 0; i < result.rows.length; i++) {
					data[result.rows[i]._id] = result.rows[i].name;
				}
			}
		});
		return data;
	}

	function getGoodsOptions() {
		let data = {};
		runAjax('get', '/sales/goods/lists', {}, function (err, result) {
			if (!err) {
				for (let i = 0; i < result.rows.length; i++) {
					data[result.rows[i]._id] = result.rows[i].name;
				}
			}
		});
		return data;
	}

	function getShopNames() {
		let data = {};
		runAjax('get', '/sales/shops/lists', {}, function (err, result) {
			if (!err) {
				for (let i = 0; i < result.rows.length; i++) {
					data[result.rows[i]._id] = result.rows[i].name;
				}
			}
		});
		return data;
	}

	function getSupplierOptions() {
		let data = {};
		runAjax('get', '/sales/suppliers/lists', {}, function (err, result) {
			if (!err) {
				for (let i = 0; i < result.rows.length; i++) {
					data[result.rows[i]._id] = result.rows[i].name;
				}
			}
		});
		return data;
	}
	function getTransportOptions() {
		let data = {};
		runAjax('get', '/sales/transport/lists', {}, function (err, result) {
			if (!err) {
				for (let i = 0; i < result.rows.length; i++) {
					data[result.rows[i]._id] = result.rows[i].name;
				}
			}
		});
		return data;
	}
	$(document).ready(function () {

		// 定价列数据
		var priColModel=[
			{label: 'ID', name: '_id', index: '_id', hidden: true, editable: false}, //width:60,
			{label: '日期', name: 'date', index: 'date', editor: "text", edittype: "text", editable: true,
				formatter: function (cellvalue, options, rowObject) {
					return (new Date(cellvalue)).format("yyyy-MM-dd hh:mm:ss");
				}, editoptions: {
					dataInit: function (elem) {
						$(elem).datetimepicker({
							// defaultDate:+1,
							dateFormat: "yy-mm-dd",
							showSecond: true,
							changeYear: true,
							changeMonth: true,
							timeFormat: 'HH:mm:ss',
							stepHour: 1,
							stepMinute: 1,
							stepSecond: 1
						});
						if ($(elem).val() == '') {
							$(elem).datetimepicker('setDate', new Date());
						}
					}
				},
				searchoptions: {
					dataInit: function (elem) {
						$(elem).datetimepicker({
							// defaultDate:new Date(),
							dateFormat: "yy-mm-dd", //日期格式
							showSecond: true,
							changeYear: true,
							changeMonth: true,
							showButtonPanel: true,
							timeFormat: 'HH:mm:ss',
							stepHour: 1,
							stepMinute: 1,
							stepSecond: 1
						});
						$(elem).datetimepicker('setDate', new Date());
					},
					sopt: ["le", "ge"]
				}
			},
			{
				label: 'dId',
				name: 'dId',
				index: 'dId',
				editor: "text",
				editable: false,
                hidden: true
			},
			{
				label: '品类',
				name: 'gId',
				index: 'gId',
				editor: "text",
				formatter: "select",
				edittype: "select",
				editable: true,
				editoptions: {
					value: getGoodsOptions(),
					dataInit: function (elem) {
						$(elem).select2({
							language: "zh-CN",
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
						});
					}
				},
				stype: 'select',
				searchoptions: {
					value: getGoodsOptions(),
					dataInit: function (elem) {
						$(elem).select2({
							language: "zh-CN",
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true
						});
					},
					sopt: ["eq", "ne"]
				}
			},
			{
				label: '供应商',
				width: 100,
				name: 'suId',
				index: 'suId',
				editor: "text",
				formatter: "select",
				edittype: "select",
				editable: true,
				editoptions: {
					value: getSupplierOptions(),
					dataInit: function (elem) {
						$(elem).css({width: "100%"}).select2({
							language: "zh-CN",
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
						});
					}
				},
				stype: 'select',
				searchoptions: {
					value: getSupplierOptions(),
					dataInit: function (elem) {
						$(elem).select2({
							language: "zh-CN",
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
							// theme: "classic",
						});
					},
					sopt: ["eq", "ne"]
				}
			},
			{
				label: '店铺',
				width: 100,
				name: 'sId',
				index: 'sId',
				search: false,
				editor: "text",
				formatter: "select",
				edittype: "select",
				editable: true,
				editoptions: {
					value: getShopNames(),
					dataInit: function (elem) {
						$(elem).select2({
							language: "zh-CN",
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
							// theme: "classic",
						});
					}
				},
				stype: 'select',
				searchoptions: {
					value: getShopNames(),
					dataInit: function (elem) {
						$(elem).select2({
							language: "zh-CN",
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
							// theme: "classic",
						});
					},
					sopt: ["eq", "ne"]
				}
			},
			{
				label: '定价',
				width: 60,
				name: 'price',
				index: 'price',
				editor: "text",
				editable: true,
				search: false,
				sortable: false,
				formatter: function (cellvalue, options, rowObject) {
					return typeof cellvalue == 'object' ? cellvalue.$numberDecimal : (cellvalue ? cellvalue : "0.00");//代替默认
				}
			},
			{
				label: '库存',
				width: 60,
				name: 'num',
				index: 'num',
				editor: "text",
				editable: false,
				search: false,
				sortable: false
			},
			{
				label: '备注', name: 'rem', index: 'rem', sortable: false, editable: true, search: false,
				edittype: "textarea", editoptions: {rows: "2", cols: "20"}
			}
		];
		// 销售单列数据
		var salesColModel = [
			{label: 'ID', name: '_id', index: '_id', hidden: true, editable: false}, //width:60
			/*{
				label: '提交',
				name: 'audit',
				index: 'audit',
				editor: "text",
				editable: false,
				search: false,
				formatter: "select",
				edittype: "select",
				editoptions: {
					value: {0: '未提交', 1: '已提交', 2: '已审核'}
				}
			},*/
			{label: '客户', name: 'cId', index: 'cId', editor: "text", edittype: "select", editable: true,
				formatter: function (cellvalue, options, rowObject) {
					var values = $("#list").jqGrid('getColProp', 'cId').editoptions.value;
					var value = values[cellvalue];
					if (!value) {
						values[cellvalue] = cellvalue;
						value = cellvalue;
						$("#list").jqGrid('setColProp', 'cId', {searchoptions: {value: values}}); //setColProp('cId',{searchoptions:{value:values}});//
					}
					return value;
				},
				editoptions: {
					value: (function () {
						return getCustomersOptions();
					})(), // getCustomersOptions()
					dataInit: function (elem) {
						$(elem).select2({
							/*width:"100%",*/
							language: "zh-CN",
							dropdownParent: $(elem).parent(),
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
							tags: true // 创建不存在的选项,相当于填写功能
						});
					}
				},
				searchoptions: {
					value: {}, // 创建完成后获取,见下面 loadComplete
					dataInit: function (elem) {
						$(elem).select2({
							language: "zh-CN",
							/*width:"100%",*/
							dropdownParent: $(elem).parent(),
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
							tags: true
						});
						$(elem).select2('val', '-1');
					},
					sopt: ["eq", "ne"]
				},
				stype: 'select',
				editrules: {required: true},
				formoptions: {elmprefix: '<span style="color: red;">*</span>'}
			},
			{label: '日期', name: 'date', index: 'date', editor: "datetime", editable: true,
				formatter: function (cellvalue, options, rowObject) {
					return (new Date(cellvalue)).format("yyyy-MM-dd hh:mm:ss");
				},
				editoptions: {
					dataInit: function (elem) {
						$(elem).datetimepicker({
							dateFormat: "yy-mm-dd",
							showSecond: true,
							changeYear: true,
							changeMonth: true,
							timeFormat: 'HH:mm:ss',
							stepHour: 1,
							stepMinute: 1,
							stepSecond: 1
						});
						if ($(elem).val() == '') {
							$(elem).datetimepicker('setDate', new Date());
						}
					}
				},
				searchoptions: {
					dataInit: function (elem) {
						$(elem).datetimepicker({
							dateFormat: "yy-mm-dd",
							showSecond: true,
							changeYear: true,
							changeMonth: true,
							timeFormat: 'HH:mm:ss',
							stepHour: 1,
							stepMinute: 1,
							stepSecond: 1
						});
						$(elem).datetimepicker('setDate', new Date());
					},
					sopt: ["le", "ge"]
				},
				editrules: {required: true},
				formoptions: {elmprefix: '<span style="color: red;">*</span>'}
			},
			{
				label: '批零',
				name: 'mode',
				index: 'mode',
				editor: "text",
				editable: true,
				search: true,
				formatter: "select",
				edittype: "select",
				editoptions: {
					defaultValue:"0",
					value: {0: '批发', 1: '零售'}
				},
				stype:'select',
				searchoptions: {
					value: {0:'批发',1:'零售'},
					defaultValue:"0",
					sopt: ["eq"]
				},
				formoptions: {elmprefix: '<span style="color: red;">*</span>'}
			},
			{
				label: '运输',
				name: 'tId',
				index: 'tId',
				editor: "text",
				formatter: "select",
				edittype: "select",
				editable: true,
				editoptions: {
					value: getTransportOptions(),
					dataInit: function (elem) {
						$(elem).select2({
							language: "zh-CN",
							dropdownParent: $(elem).parent(),
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
							// theme: "classic",
						});
					}
				},
				editrules: {required: true},
				formoptions: {
					// rowpos: 3, colpos: 1,
					elmprefix: '<span style="color: red;">*</span>'
				},
				stype: 'select',
				searchoptions: {
					value: {},
					dataInit: function (elem) {
						$(elem).css({width: "100%"}).select2({
							language: "zh-CN",
							dropdownParent: $(elem).parent(),
							placeholder: {
								id: '-1', // the value of the option
								text: '请选择一个选项'
							},
							allowClear: true,
							// theme: "classic",
						});
					},
					sopt: ["eq", "ne"]
				}
			},
			{
				label: '支付',
				name: 'payId',
				index: 'payId',
				editor: "text",
				search: false,
				formatter: "select",
				edittype: "select",
				editable: true,
				editoptions: {
					value: {0: "现金", 1: "挂账", 2: "支付宝", 3: "微信", 4: "其他"}
				},
				formoptions: {elmprefix: '<span style="color: red;">*</span>'}
			},
			{
				label: '合计', name: 'total', index: 'total', editor: "text", editable: false, search: false,
				/*editoptions: { defaultValue: '0.00'},*/
				formatter: function (cellvalue, options, rowObject) {
					return typeof cellvalue == 'object' ? cellvalue.$numberDecimal : (cellvalue ? cellvalue : "0.00");//代替默认
				}
			}
		];
		// 销售详细列数据
        var salesItemsColModel = [{label: 'ID', name: '_id', index: '_id', editor: "text", editable: false, hidden: true},
	        {label: '总库', name: 'dId', index: 'dId', editor: "text", editable: false, hidden: true},
	        {label: '分库', name: 'subId', index: 'subId', editor: "text", editable: false, hidden: true},
	        {label: '品类', name: 'gId', index: 'gId', editor: "text", formatter: "select", width: "100",
		        edittype: "select", editable: false, editoptions: {
			        value: {},// getGoodsOptions()
		        }
	        },
	        {
		        label: '数量',
		        name: 'num',
		        index: 'num',
		        editor: "text",
		        editable: true,
		        formatter: "integer",
		        width: "80",
		        editrules: {required: true, integer: true},
		        editoptions: {defaultValue: '1'},
		        formoptions: {elmprefix: '<span style="color: red;">*</span>'}
	        },
	        {
		        label: '应收', name: 'should', index: 'should', editor: "text", editable: false, search: false,
		        /*editoptions: { defaultValue: '0.00'},*/
		        formatter: function (cellvalue, options, rowObject) {
			        return typeof cellvalue == 'object' ? cellvalue.$numberDecimal : (cellvalue ? cellvalue : "0.00");//代替默认
		        }
	        },
	        {
		        label: '实收',
		        name: 'proceed',
		        index: 'proceed',
		        editor: "text",
		        editable: true,
		        search: false,
		        /*editrules: {required: true},*/
		        editoptions: {defaultValue: '0.00'},
		        formoptions: {elmprefix: '<span style="color: red;">*</span>'},
		        formatter: function (cellvalue, options, rowObject) {
			        return typeof cellvalue == 'object' ? cellvalue.$numberDecimal : (cellvalue ? cellvalue : "0.00");
		        }
	        },
	        {
		        label: '欠款', name: 'arrears', index: 'arrears', editor: "text", search: false, editable: true,
		        formatter: function (cellvalue, options, rowObject) {
			        return typeof cellvalue == 'object' ? cellvalue.$numberDecimal : (cellvalue ? cellvalue : "0.00");
		        },
		        /*editrules: {required: true},*/
                editoptions: {defaultValue: '0.00'},
		        formoptions: {elmprefix: '<span style="color: red;">*</span>'}
	        },
	        {
		        label: '备注', name: 'rem', index: 'rem', sortable: false, editable: true, search: false,
		        edittype: "textarea",  editoptions: {rows: "2", cols: "23"}
	        }
        ];
		jQuery("#list").jqGrid({
			// url:'/sales/lists', //
			datatype: "json",
			mtype: "GET",
			shrinkToFit: true,
			height: 'auto',
			width: "100%",
			deepempty: true,
			autowidth: true,
			// postData: {Audit: 1},
			colModel: salesColModel,
			sortname: '_id',
			sortorder: 'desc', // asc 升序
			viewrecords: true,
			rowNum: 5,
			rowList: [5, 10],
			pager: "#pager",
			caption: "销售单-" +'<%= shop %>',
			multiselect: false,
			// toppager:true,
			editable: true,
			jsonReader: {
				id: "_id",
				root: "rows",
				page: "page",
				total: "total",
				records: "records",
				repeatitems: false
			},
			loadComplete: function (data) {
			},
			onSelectRow: function (rowid, status) {
				// $("#list").jqGrid("expandSubGridRow", rowid);
			},
			subGrid: true,
			subGridOptions: {
				"plusicon": "ui-icon-triangle-1-e",
				"minusicon": "ui-icon-triangle-1-s",
				"openicon": "ui-icon-arrowreturn-1-e",
				// load the subgrid data only once
				// and the just show/hide
				"reloadOnExpand": false,
				// select the row when the expand column is clicked
				"selectOnExpand": true
			},
			subGridRowExpanded: function (subGrid_id, row_id) {
				var subGrid_table_id, pager_id;
				subGrid_table_id = subGrid_id + "_t";
				pager_id = "p_" + subGrid_table_id;
				$("#" + subGrid_id).html("<table id='" + subGrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll no-print'></div>");
				var options = {
					// url: 'clientArray' ,//+ row_id,
					datatype: "json",
					mtype: "GET",
					shrinkToFit: true,
					// toppager: true,
					editable: true,
					rownumbers: true,
					deepempty: true,
					height: 'auto', //auto
					width: 700,
					// autowidth: true,
					colModel: salesItemsColModel,
					sortname: '_id',
					sortorder: 'asc',
					viewrecords: true,
					rowNum: -1,
					pager: "#" + pager_id,
					caption: "明细列表",
					multiselect: false,
					jsonReader: {
						id: "_id",
						root: "rows",
						page: "page",
						total: "total",
						records: "records",
						repeatitems: false
					},
					loadComplete: function (xhr) {
						// $("#" +subGrid_table_id).jqGrid('setColProp','gId',{searchoptions:{value:values}});
					}
				};
				var audit = $("#list").jqGrid("getCell", row_id, "audit");
				if (audit == 1) {
					options.url = '/sales/lists/' + row_id;
				}
				jQuery("#" + subGrid_table_id).jqGrid(options);
				var values = $("#list1").getColProp('gId').searchoptions.value;
				$("#" + subGrid_table_id).jqGrid('setColProp', 'gId', {editoptions: {value: values}});
				jQuery("#" + subGrid_table_id).jqGrid('navGrid', '#' + pager_id, {
						/*cloneToTop: true,*/
						add: true,
						edit: true,
						del: true,
						search: false,
						refresh: false
					},
					{
						checkOnSubmit: false, closeAfterEdit: true, reloadAfterSubmit: false, modal: true,
						url: 'clientArray',// url: "/sales/" + row_id + "/",
						mtype: "put",
						beforeShowForm: function (form) {
							form.find("#num").parent().parent().hide();
							return [true, ''];
						},
						onclickSubmit: function (params, postData) {
							// params.url = "/sales/" + row_id + '/' + postData[subGrid_table_id + '_id'];
							return [true, ''];
						},
						beforeSubmit: function (postData, formid) {
							// var oldId=$("#" +subGrid_table_id).jqGrid('getGridParam','selrow');
							var oData = $("#" + subGrid_table_id).jqGrid('getRowData', postData[subGrid_table_id + '_id']);
							var stocksNum = $("#list1").jqGrid('getCell', postData.subId,'num');
							if (stocksNum < postData.num - oData.num) {
								return [false, "出货量超过了库存!"];
							}
							var total =  $("#list").jqGrid('getCell', row_id,'total');
							total -= oData.proceed;
							total += Number(postData.proceed);
							$("#list").jqGrid("setCell", row_id, "total",total);
							return [true, ''];
						},
						afterSubmit: function (response, postData) {
							return [true, ''];
						}
					},  // edit sub
					{
						checkOnSubmit: false,
						closeAfterAdd: true,
						reloadAfterSubmit: false,
						modal: true,
						jqModal: true,
						addedrow: 'last',
						url: 'clientArray',// url: "/sales/" + row_id,
						mtype: "post",
						beforeShowForm: function (form) {
							var sId = $('#list1').jqGrid('getGridParam', 'selrow');
							if (!sId) {
								$("#info").text('请选中库存列表中的条目!');
								$("#dialog-message").dialog("open");
								form.dialog("close");
								return [false, ''];
							}
							form.find("#proceed").parent().parent().hide();
							form.find("#arrears").parent().parent().hide();
						},
						onclickSubmit: function (params, postData) {
							return [true, ''];
						},
						beforeSubmit: function (postData, formid) {
							var sId = $('#list1').jqGrid('getGridParam', 'selrow');
							var rowData = $("#list1").jqGrid('getRowData', sId);
							if (postData.num > Number(rowData.num)) {
								return [false, "出货量超过了库存!"];
							}
							postData._id = jsShortId.uuid();
                            postData.dId = rowData.dId;
							postData.subId = rowData._id;
							postData.gId = rowData.gId;
							postData.should =  Number(postData.num) * Number(rowData.price);
							postData.proceed = postData.should;
							return [true, '']; //return [true, "", jqXhr.responseJSON.id];
						},
						afterSubmit: function (response, postData) {
							//var result=response.responseJSON;
							// postData.id = result.id;
							var total = $("#list").jqGrid("getCell", row_id, "total");
							total = Number(total) + postData.proceed;
							$("#list").jqGrid("setCell", row_id, "total", total);// 合计实收
							var stockNum = $("#list1").jqGrid('getCell', postData.subId, 'num');
							var exit = stockNum - postData.num;
							$("#list1").jqGrid("setCell", postData.subId, "num", exit);
							return [true, "", postData._id];
						}
					},// add sub
					{
						checkOnSubmit: false, reloadAfterSubmit: false, modal: true,
						url: 'clientArray', // url: "/sales/" + row_id ,
						mtype: "delete",
						onclickSubmit: function (params, postData) {
							var rowData = $("#" + subGrid_table_id).jqGrid('getRowData', postData);
							// params.url = "/sales/" + row_id + "/" + postData + "?pId=" + rowData.pId +"&&oldNum=" + rowData.num;
							return [true, ''];
						},
						beforeSubmit: function (id, formid) {
							var oData = $("#" + subGrid_table_id).jqGrid('getRowData', id );
							var total =  $("#list").jqGrid('getCell', row_id,'total');
							total -= oData.proceed;
							$("#list").jqGrid("setCell", row_id, "total",total);
							var oNum = $("#list1").jqGrid("getCell", oData.subId, "num");
							$("#list1").jqGrid("setCell", oData.subId, "num",Number(oNum)+Number(oData.num));
							return [true, ''];
						},
						afterSubmit: function (response, postData) {
							return [true, ''];
						}
					}, // del sub
					{multipleSearch: true, closeAfterSearch: true} // search
				);
				// $('#'+pager_id).hide();
			}
		});
		// var values = $("#list").getColProp('cId').editoptions.value;
		// $("#list").jqGrid('setColProp', 'cId', {searchoptions: {value: values}});

		jQuery("#list").jqGrid('navGrid', '#pager', {
				add: true, edit: true, del: true, search: false, refresh: false,
				edittitle: "提交", editicon: 'ui-icon-disk', addtitle: '添加销售单', deltitle: '删除销售单'
			},
			{
				checkOnSubmit: false, closeAfterEdit: true, reloadAfterSubmit: false,
				modal: true, height: "100%", width: "100%",
				url: "/sales",
				mtype: "post",
				beforeShowForm: function (form) {
					// $("#list").jqGrid('setColProp', 'proceed', { editrules:{required:true,number:true}});
					// form.find('#account').attr('readOnly',true);//把编辑框中的字段设置为只读的。
				},
				onclickSubmit: function (params, postData) {
					var audit = $("#list").jqGrid("getCell", postData.list_id, "audit");
					if (audit == 1) {
						params.url = "/sales/" + postData.list_id;
						params.mtype = 'put';
					}
					return [true, ''];
				},
				beforeSubmit: function (postData, formid) {
					var subGrid = $('#' + 'list_' + postData.list_id + '_t').jqGrid('getRowData');
					if (subGrid.length == 0) {
						return [false, '请填写详细项目!'];
					}
					postData.lists = subGrid;
					return [true, ''];
				},
				afterSubmit: function (response, postData) {
					$("#list").jqGrid("delRowData", postData.id);
					return [true, ''];
				}
			}, // edit
			{
				checkOnSubmit: false, closeAfterAdd: true, reloadAfterSubmit: false, modal: true,
				jqModal: true, addedrow: 'first', height: "100%", width: "100%",
				url: "clientArray", // /sales
				mtype: "post",
				beforeShowForm: function (form) {
					form.find("#payId").parent().parent().hide();
					form.find("#proceed").parent().parent().hide();
					form.find("#arrears").parent().parent().hide();
					form.find("#date").val((new Date()).format("yyyy-MM-dd hh:mm:ss"));
					//  $("#list").jqGrid('setColProp', 'proceed', { editrules:{required:false}});
				},
				onclickSubmit: function (params, postData) {
					return [true, ''];
				},
				beforeSubmit: function (postData, formid) {
					if (null == postData.cId) {
						return [false, '请选或填写择客户'];
					}
					postData._id = jsShortId.gen(15);
					postData.audit = 0;
					// postData.should = 0;
					return [true, '']; //return [true, "", jqXhr.responseJSON.id];
				},
				afterSubmit: function (response, postData) {
					var result = response.responseJSON;
					// postData.id = result.id;
					return [true, "", postData._id];
				},
				afterComplete: function (response, postData, formid) {
					$("#list").jqGrid("expandSubGridRow", postData._id);
				}
			}, // add
			{
				checkOnSubmit: false, reloadAfterSubmit: false, modal: true,
				url: "clientArray", // /sales
				mtype: "delete",
				onclickSubmit: function (params, id) {
					var audit = $("#list").jqGrid("getCell", id, "audit");
					if (audit == 1) {
						params.url = "/sales/" + id;
					}
					return [true, ''];
				},
				beforeSubmit: function (id, formid) {
					var subGrid = $('#' + 'list_' + id + '_t').jqGrid('getRowData');
					for (var i = 0; i < subGrid.length; i++) {
						var num = Number(subGrid[i].num);
						var surplus = Number($("#list1").jqGrid('getCell', subGrid[i].subId,'num'));
						surplus += num;
						$("#list1").jqGrid("setCell", subGrid[i].subId, "num", surplus);
					}
					return [true, ''];
				},
				afterSubmit: function (response, postData) {

					return [true, ''];
				}
			}, // del
			{
				multipleSearch: true, multipleGroup: false, closeAfterSearch: true,
				beforeShowSearch: function (form) {
					var rowsData = $("#list").jqGrid('getRowData');
					for (var i = 0; i < rowsData.length; i++) {
						if (rowsData[i].audit == 0) {
							$("#info").text('有未提交的数据,不能搜索!');
							$("#dialog-message").dialog("open");
							form.dialog("close");
							return;
						}
					}
					$("#list").jqGrid('setGridParam', {url: "/sales/lists"});
					return [true, ""];
				}
			} // search
		).jqGrid('navButtonAdd', '#pager', { // sub un
            caption: '',
            title: '打印',
            buttonicon:"ui-icon-print",
            onClickButton: function () {
                $("#list_1").print({
                    title:"销售单",
                    stylesheet:"/css/css.css"
                    });
            },
        });;
		jQuery("#list1").jqGrid({
			url: '/sales/subStocks',
			datatype: "json",
			mtype: "GET",
			shrinkToFit: true,
			deepempty: true,
			height: 'auro',
			width: "100%",
			autowidth: true,
			colModel: priColModel,
			sortname: '_id',
			sortorder: 'desc',
			viewrecords: true,
			rowNum: 10,
			rowList: [10, 20, 30],
			pager: "#pager1",
			caption: "定价列表",
			multiselect: false,
			jsonReader: {
				id: "_id",
				root: "rows",
				page: "page",
				total: "total",
				records: "records",
				repeatitems: false
			},
			loadComplete: function (xhr) {
			}
		});
		jQuery("#list1").jqGrid('navGrid', '#pager1', {
				add: false,
				edit: false,
				del: false,
				search: true,
				refresh: false
			},{
        }, {
            beforeShowForm: function (form) {
            },
        }, {}, {multipleSearch: true, closeAfterSearch: true});
	});
</script>
</body>
</html>
